package com.campusbook.controller;

import com.campusbook.model.Book;
import com.campusbook.service.BookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.validation.Valid;
import java.io.IOException;
import java.util.List;

/**
 * 图书控制器
 */
@Controller
@RequestMapping("/books")
public class BookController {

    @Autowired
    private BookService bookService;

    @GetMapping
    public String listBooks(Model model) {
        List<Book> books = bookService.findAvailableBooks();
        model.addAttribute("books", books);
        return "books/list";
    }

    @GetMapping("/my")
    public String myBooks(Model model, Authentication authentication) {
        Long ownerId = getCurrentUserId(authentication);
        List<Book> books = bookService.findByOwnerId(ownerId);
        model.addAttribute("books", books);
        return "books/my";
    }

    @GetMapping("/add")
    public String showAddForm(Model model) {
        model.addAttribute("book", new Book());
        return "books/add";
    }

    @PostMapping("/add")
    public String addBook(@Valid @ModelAttribute("book") Book book,
                         BindingResult result,
                         @RequestParam("coverImageFile") MultipartFile coverImageFile,
                         Authentication authentication,
                         RedirectAttributes redirectAttributes) throws IOException {
        
        if (result.hasErrors()) {
            return "books/add";
        }

        Long ownerId = getCurrentUserId(authentication);
        book.setOwnerId(ownerId);
        book.setStatus("AVAILABLE");

        // 处理图片上传
        if (!coverImageFile.isEmpty()) {
            String imagePath = bookService.saveCoverImage(coverImageFile);
            book.setCoverImage(imagePath);
        }

        bookService.save(book);
        redirectAttributes.addFlashAttribute("successMessage", "图书发布成功");
        return "redirect:/books/my";
    }

    @GetMapping("/{id}")
    public String bookDetail(@PathVariable Long id, Model model) {
        Book book = bookService.findById(id);
        model.addAttribute("book", book);
        return "books/detail";
    }

    @PostMapping("/{id}/borrow")
    public String borrowBook(@PathVariable Long id,
                           Authentication authentication,
                           RedirectAttributes redirectAttributes) {
        Long borrowerId = getCurrentUserId(authentication);
        boolean success = bookService.borrowBook(id, borrowerId);
        
        if (success) {
            redirectAttributes.addFlashAttribute("successMessage", "借阅成功");
        } else {
            redirectAttributes.addFlashAttribute("errorMessage", "借阅失败，图书可能已被借出");
        }
        
        return "redirect:/books/" + id;
    }

    private Long getCurrentUserId(Authentication authentication) {
        // 这里简化处理，实际应该从UserDetails中获取
        return 1L;
    }
}
